package ch.unisi.inf.java.project.riskbami.model;

import java.io.*;
import java.util.HashMap;
import java.awt.*;

/**
 * CountryColorReader is a class that provide to get an HashMap<Color, String> from
 * a plain text file that contains all the countries that a map has with its respective
 * color.
 * 
 * The file must be structured as follows:
 * 
 * Switzerland 100 200 23
 * Italy 23 42 0
 * ...
 * 
 * Where the first word on each row has to be the name of the country and the remaining 3 numbers,
 * separated by an empty space, represent the RGB values of the color.
 * 
 * @author minellir@lu.unisi.ch
 */
public final class CountryColorReader{

    private final HashMap<Color, String> colorsToCountry;
    
    /**
     * Constructor for the class CountryColorReader
     */
    public CountryColorReader(){
        colorsToCountry = new HashMap<Color, String>();
    }
    
    /**
     * Maps the input file from a simple .txt file into an HashMap<Color, String>
     */
    public final HashMap<Color, String> getFileAsHashmap(final FileInputStream file){
        try{
            // Get the object of DataInputStream
            final DataInputStream input = new DataInputStream(file);
            final BufferedReader buffer = new BufferedReader(new InputStreamReader(input));
            
            String contryWithColor;
            
            String[] splittedLine = new String[4];
            String countryName;
            Color actualColor;
            
            //Read File Line By Line
            while ((contryWithColor = buffer.readLine()) != null)   {
                splittedLine = contryWithColor.split(" ");
                
                countryName = splittedLine[0];
                actualColor = new Color(Integer.parseInt(splittedLine[1]), Integer.parseInt(splittedLine[2]), Integer.parseInt(splittedLine[3]));
                
                //Filling the HashMap line by line
                colorsToCountry.put(actualColor, countryName);
            }
            //Close the input stream
            input.close();
            
        }catch (final Exception e){
            //Catch exception if any..
            System.err.println("Error: " + e.getMessage());
        }
    //Return the HashMap
    return colorsToCountry;
  }
}